<?php
/*
Plugin Name: eSfaturi.ro - Categories widget
Plugin URI: 
Description: Displays categories tree
Version: 1.0.0
Author: Sergiu Bologa
Author URI: 
License: GPL2
*/

// Start class
class esf_categories_widget extends WP_Widget {
	
	// Constructor
	function esf_categories_widget() {
		$widget_ops = array( 'classname' => 'esf_categories_widget', 'description' => 'Displays categories tree' );
		
		// Widget Settings
		$control_ops = array( 'id_base' => 'esf_categories_widget' ); // Widget Control Settings
		$this->WP_Widget( 'esf_categories_widget', 'Categories tree', $widget_ops, $control_ops ); // Create the widget
	}

	// Extract Args
	function widget($args, $instance) {
		extract( $args );
		$title = apply_filters('widget_title', $instance['title']); // the widget title

		// Before widget
		echo $before_widget;
		
		// Title of widget
		if ( $title ) { echo $before_title . $title . $after_title; }

		// Widget output
		$categories = get_categories(array('exclude' => '0', 'orderby' => 'name', 'hierarchical' => true));
		$dir = get_bloginfo ( 'template_directory' );
		
		echo "<ul id='categories-tree'>";
		foreach($categories as $category) {
			if ($category->parent == 0){
				echo '<li>';
					//echo '<img src="'.$dir.'/styles/images/category-minus.gif" alt="" />';
					echo '<a href="'.get_category_link($category->term_id).'" id="cat-'.$category->term_id.'" title="'.$category->cat_name.'">'. $category->cat_name.'</a>';
				
					echo '<ul>';
				foreach($categories as $child){
					if ($child->parent == $category->cat_ID){
						$childLink = esc_url( get_permalink( get_page_by_title( $child->cat_name, 'OBJECT', 'post' ) ) );
						$title = esc_attr( sprintf( __( "%s" ), $child->name ) );
						echo '<li><a href="'.$childLink.'" title="'.$title.'" id="cat-'.$child->term_id.'">'.$child->cat_name.'</a></li>';
					}
				}
					echo '</ul>';
				echo '</li>';
			}
		}
		echo "</ul>";
		
		// After widget
		echo $after_widget;
	}
	
	// Update Settings
	function update($new_instance, $old_instance) {
 		$instance['title'] = strip_tags($new_instance['title']);
 		return $instance;
 	}
	
	// Widget Control Panel
	function form($instance) {
 		$defaults = array( 'title' => 'Categorii' );
 		$instance = wp_parse_args( (array) $instance, $defaults ); ?>

 		<p>
			<label for="<?php echo $this->get_field_id('title'); ?>">Title:</label>
 			<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $instance['title']; ?>" />
 		</p>
 			
        <?php 
	}
}

// End class category_related_posts_widget
add_action('widgets_init', create_function('', 'return register_widget("esf_categories_widget");'));
?>